package com.bsg.upm.task;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dao.MonitorResourceDao;
import com.bsg.upm.entity.MonitorResourceEntity;
import com.bsg.upm.entity.SiteEntity;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.service.BaseService;

@Service
public class DataCollectionTask extends BaseService {

	@Resource
	private MonitorResourceDao monitorResourceDao;
	
	public void dataCollection() {
		try {
			logger.info("主机数量、容器数量采集");
			List<SiteEntity> sites = siteDao.list(null);
			Date date = systemDao.getCurrentDateTime();
			for (SiteEntity site : sites) {
				String siteId = site.getId();
				String url = "/" + SysConstants.MGM_VERSION + "/hosts";
				RespJson httpRespJson = this.sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url, 3, 10000);
				if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
					JSONArray hostJsonArr = (JSONArray) httpRespJson.getData();
					int hostCnt = hostJsonArr.size();
					int containerCnt = 0;
					for (int j = 0; j < hostJsonArr.size(); j++) {
						JSONObject hostJson = hostJsonArr.getJSONObject(j);
						JSONArray containerJsonArr = hostJson.getJSONArray("containers");
						if (containerJsonArr != null) {
							containerCnt += containerJsonArr.size();
						}
					}
					Calendar cal = Calendar.getInstance();
					cal.setTime(date);
					cal.set(Calendar.MINUTE, 0);
					cal.set(Calendar.SECOND, 0);
					cal.set(Calendar.MILLISECOND, 0);
					Long timestamp = cal.getTimeInMillis();
					
					MonitorResourceEntity monitorResource = monitorResourceDao.getByTimestampAndSiteId(timestamp, siteId);
					if (monitorResource == null) {
						monitorResource = new MonitorResourceEntity();
						monitorResource.setTimestamp(timestamp);
						monitorResource.setSiteId(siteId);
						monitorResource.setHostCnt(hostCnt);
						monitorResource.setContainerCnt(containerCnt);
						int servCnt = servDao.countBySiteId(siteId);
						monitorResource.setServCnt(servCnt);
						monitorResource.setDatetime(date);
						monitorResourceDao.save(monitorResource);
					} else {
						monitorResource.setHostCnt(hostCnt);
						monitorResource.setContainerCnt(containerCnt);
						int servCnt = servDao.countBySiteId(siteId);
						monitorResource.setServCnt(servCnt);
						monitorResource.setDatetime(date);
						monitorResourceDao.update(monitorResource);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
